<template>
  <div class="app-container">
    <!-- <h1 style="margin-top:30px;width:100px;margin:0 auto">shop</h1> -->
    <EsHeader :title="title"></EsHeader>
    <EsGoods v-for="item in goodlist" :key="item.id" :id="item.id" :thumb="item.goods_img" :title="item.goods_name"
      :price="item.goods_price" :count="item.goods_count" @stateChange="onChangeState"
      @countChange="onGoodsCountChange">
    </EsGoods>
    <EsFooter @fullChange="onFullStateChange" :amout="amout" :total="total"></EsFooter>
  </div>
</template>

<script>
import EsHeader from "./components/EsHeader/index.vue";
import EsGoods from "./components/EsGoods/index.vue";
import EsFooter from "./components/EsFooter/index.vue";

export default {
  name: "App",
  components: {
    EsHeader,
    EsGoods,
    EsFooter,
  },
  data() {
    return {
      title: "购物车案例",
      goodlist: [],
    };
  },
  methods: {
    // 获取接口数据进行处理
    async getlist() {
      const { data: res } = await this.$https.get("cart");
      // 判断请求是否成功
      if (res.status !== 200) return alert("请求商品列表数据失败");
      // 将请求数据存放到data的数组里进行数据的渲染
      const { list } = res;
      return (this.goodlist = list);
    },
    // 全选与非全选
    onFullStateChange(isFull) {
      this.goodlist.forEach(x => (x.goods_state = isFull))
    },
    // state状态是否一致
    onChangeState(val) {
      // let goodstate = good.goods_state;
      // console.log(goodstate);
      // if (checked != state) {
      //   state = checked;
      // }
      const findState = this.goodlist.find(x => x.id === val.id);
      if (findState) {
        findState.goods_state = val.value;
      }
      return findState;
    },
    // onGoodsCountChange （更新商品数量）
    onGoodsCountChange(val) {
      const findResult = this.goodlist.find(x => x.id === val.id)
      if (findResult) {
        findResult.goods_count = val.value
      }
      console.log(val);
    }
  },
  computed: {
    // 已勾选的商品的价格
    amout() {
      let sum = 0;
      this.goodlist.filter(x => x.goods_state).forEach(x => {
        sum += x.goods_price * x.goods_count;
      })
      return sum;
    },
    // 勾选商品的总数量
    total() {
      let t = 0;
      this.goodlist.filter(x => x.goods_state).forEach(x => {
        t += x.goods_count
      })
      return t;
    },
  },

  created() {
    this.getlist();
  },
};
</script>
<style lang="less" scoped>
.app-container {
  padding: 45px 0 50px 0;
}
</style>
